package www.dashu.com.controller;

import www.dashu.com.api.CommonResult;
import www.dashu.com.service.RedisService;
import www.dashu.com.domain.SysCompany;
import www.dashu.com.dto.CompanyQuery;
import www.dashu.com.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@Api(tags = "SysCompanyController", description = "商户管理")
@RequestMapping("/company")
public class SysCompanyController
{

    @Autowired
    SysCompanyService companyService;
    @Autowired
    RedisService redisService;

    @ApiOperation(value = "商户列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Page<SysCompany>> list(CompanyQuery companyQuery) {

        try {
            Page<SysCompany> pageData = companyService.findAll(companyQuery);
            return CommonResult.success(pageData);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @ApiOperation(value = "新增商户")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult create(@RequestBody SysCompany company) {
        company.setId(companyService.createId(company));
        company.setCreateTime(new Date());
        company.setUpdateTime(new Date());
        companyService.save(company);
        return CommonResult.success();
    }

    @ApiOperation(value = "修改商户")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(@RequestBody SysCompany company) {
        company.setUpdateTime(new Date());
        companyService.save(company);
        return CommonResult.success();
    }

    @ApiOperation(value = "删除商户")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public CommonResult delete(@RequestBody SysCompany company) {
        companyService.deleteById(company.getId());
        return CommonResult.success();
    }

}
